import React, { useState, useEffect, useRef } from 'react';
import './Register.css';
import Bottom from '../components/bottom/Bottom';
import { Top } from '../components/top/Top';
import { accountService } from '../../service/accountService';
import { common_utils } from '../../utils/utils';

const Register = () => {
  const [formData, setFormData] = useState({
    username: '',
    password: '',
    code: '',
    firstname: '',
    lastname: '',
    email: '',
    phone: '',
    addr1: '',
    addr2: '',
    city: '',
    state: '',
    zip: '',
    country: '',
    langpref: '',
    favcategory: '',
    file: null,
  });

  const [usernameTips, setUsernameTips] = useState('');
  const [usernameClass, setUsernameClass] = useState('');
  const [showInfo, setShowInfo] = useState(false);
  const [signOnMsg, setSignOnMsg] = useState(null);
  const [captchaError, setCaptchaError] = useState('');
  const [captchaText, setCaptchaText] = useState(''); // 存储生成的验证码文本
  const canvasRef = useRef(null); // 用于引用 Canvas

  // 生成随机验证码
  const generateCaptcha = () => {
    const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    let text = '';
    for (let i = 0; i < 4; i++) {
      text += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    setCaptchaText(text);
    drawCaptcha(text);
    setFormData((prev) => ({ ...prev, code: '' })); // 清空用户输入
    setCaptchaError(''); // 清空错误提示
  };

  // 在 Canvas 上绘制验证码
  const drawCaptcha = (text) => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 设置背景
    ctx.fillStyle = '#f0f0f0';
    ctx.fillRect(0, 0, canvas.width, canvas.height);

    // 绘制干扰线
    for (let i = 0; i < 4; i++) {
      ctx.strokeStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`;
      ctx.beginPath();
      ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
      ctx.stroke();
    }

    // 绘制验证码文本
    ctx.font = '30px Arial';
    ctx.fillStyle = '#333';
    for (let i = 0; i < text.length; i++) {
      ctx.fillText(text[i], 10 + i * 30, 35 + Math.random() * 10 - 5);
      ctx.fillStyle = `rgb(${Math.random() * 255},${Math.random() * 255},${Math.random() * 255})`;
    }
  };

  // 初始化时生成验证码
  useEffect(() => {
    generateCaptcha();
  }, []);

  // 处理输入变化
  const handleInputChange = (e) => {
    const { name, value, files } = e.target;
    if (name === 'file') {
      setFormData((prev) => ({
        ...prev,
        file: files[0] || null,
      }));
    } else {
      setFormData((prev) => ({
        ...prev,
        [name]: value,
      }));
    }
  };

  // 检查用户名是否存在
  const handleUsernameBlur = async () => {
    if (!formData.username) return;
    try {
      const response = await fetch(`/usernameExist?username=${formData.username}`);
      const text = await response.text();
      const trimmed = text.trim();
      if (trimmed === 'Exist') {
        setUsernameClass('errorTips');
        setUsernameTips('invalid username');
      } else if (trimmed === 'Not Exist') {
        setUsernameClass('okTips');
        setUsernameTips('available username');
      } else {
        setUsernameClass('errorTips');
        setUsernameTips('unexpected response');
      }
    } catch (error) {
      console.error('Username check error:', error);
      setUsernameClass('errorTips');
      setUsernameTips('error checking username');
    }
  };

  // 切换详细信息显示
  const toggleInfo = () => {
    setShowInfo((prev) => !prev);
  };

  // 验证验证码
  const validateCaptcha = () => {
    return formData.code.toLowerCase() === captchaText.toLowerCase();
  };

  // 表单提交
  const handleSubmit = (e) => {
    e.preventDefault();

    // 验证验证码
    if (!validateCaptcha()) {
      setCaptchaError('Invalid verification code');
      generateCaptcha(); // 验证码错误时刷新
      return;
    }

    // 验证码正确，继续注册
    accountService.register(formData, (response) => {
      if (response.code === 1000) {
        alert('Registration successful');
        generateCaptcha(); // 注册成功后刷新验证码
         common_utils.toLogin();
      } else {
        setSignOnMsg(response.msg || 'Registration failed');
        generateCaptcha(); // 注册失败也刷新验证码
      }
    });
  };

  return (
    <div className="page-wrapper">
      <Top />
      <div className="Catalog">
        {signOnMsg && <p style={{ color: 'red' }}>{signOnMsg}</p>}
        <form onSubmit={handleSubmit}>
          <h2>Register</h2>
          <p>
            <label htmlFor="file">User Image:</label>
            <input
              type="file"
              id="file"
              name="file"
              accept="image/*"
              onChange={handleInputChange}
            />
          </p>
          <p>
            <label htmlFor="username">Username:</label>
            <i>
              <img src={require('../../images/user.png')} alt="user icon" />
            </i>
            <input
              className="user"
              type="text"
              name="username"
              placeholder="username"
              id="username"
              value={formData.username}
              onChange={handleInputChange}
              onBlur={handleUsernameBlur}
              required
            />
            <span id="usernameTips" className={usernameClass}>
              {usernameTips}
            </span>
          </p>

          <p>
            <label htmlFor="password">Password:</label>
            <i>
              <img src={require('../../images/password.png')} alt="password icon" />
            </i>
            <input
              className="user"
              type="password"
              name="password"
              id="password"
              placeholder="password"
              value={formData.password}
              onChange={handleInputChange}
              required
            />
          </p>

          <p>
            <label htmlFor="code">Verification Code:</label>
            <i>
              <img src={require('../../images/code.png')} alt="code icon" />
            </i>
            <input
              className="user"
              type="text"
              name="code"
              id="code"
              placeholder="Enter code"
              value={formData.code}
              onChange={handleInputChange}
              required
            />
            <canvas
              ref={canvasRef}
              width="120"
              height="50"
              style={{ cursor: 'pointer', marginLeft: '10px', verticalAlign: 'middle' }}
              onClick={generateCaptcha}
            />
            {captchaError && <span style={{ color: 'red', marginLeft: '10px' }}>{captchaError}</span>}
          </p>

          <div className="whole">
            <img
              className="btnImg show"
              src={require('../../images/down.png')}
              alt="toggle"
              onClick={toggleInfo}
              style={{ cursor: 'pointer' }}
            />
            {showInfo && (
              <div className="Information">
                <label>
                  First Name:
                  <input
                    className="user"
                    type="text"
                    name="firstname"
                    placeholder="firstname"
                    value={formData.firstname}
                    onChange={handleInputChange}
                  />
                </label>
                <label>
                  Last Name:
                  <input
                    className="user"
                    type="text"
                    name="lastname"
                    placeholder="lastname"
                    value={formData.lastname}
                    onChange={handleInputChange}
                  />
                </label>
                <label>
                  Email:
                  <input
                    className="user"
                    type="email"
                    name="email"
                    placeholder="email"
                    value={formData.email}
                    onChange={handleInputChange}
                  />
                </label>
                <label>
                  Phone:
                  <input
                    className="user"
                    type="tel"
                    name="phone"
                    placeholder="phone"
                    value={formData.phone}
                    onChange={handleInputChange}
                  />
                </label>
                <label>
                  Address 1:
                  <input
                    className="user"
                    type="text"
                    name="addr1"
                    placeholder="address1"
                    value={formData.addr1}
                    onChange={handleInputChange}
                  />
                </label>
                <label>
                  Address 2:
                  <input
                    className="user"
                    type="text"
                    name="addr2"
                    placeholder="address2"
                    value={formData.addr2}
                    onChange={handleInputChange}
                  />
                </label>
                <label>
                  City:
                  <input
                    className="user"
                    type="text"
                    name="city"
                    placeholder="city"
                    value={formData.city}
                    onChange={handleInputChange}
                  />
                </label>
                <label>
                  State:
                  <input
                    className="user"
                    type="text"
                    name="state"
                    placeholder="state"
                    value={formData.state}
                    onChange={handleInputChange}
                  />
                </label>
                <label>
                  Zip:
                  <input
                    className="user"
                    type="text"
                    name="zip"
                    placeholder="zip"
                    value={formData.zip}
                    onChange={handleInputChange}
                  />
                </label>
                <label>
                  Country:
                  <input
                    className="user"
                    type="text"
                    name="country"
                    placeholder="country"
                    value={formData.country}
                    onChange={handleInputChange}
                  />
                </label>
                <label>
                  Language Preference:
                  <input
                    className="user"
                    type="text"
                    name="langpref"
                    placeholder="langpref"
                    value={formData.langpref}
                    onChange={handleInputChange}
                  />
                </label>
                <label>
                  Favorite Category:
                  <input
                    className="user"
                    type="text"
                    name="favcategory"
                    placeholder="favcategory"
                    value={formData.favcategory}
                    onChange={handleInputChange}
                  />
                </label>
              </div>
            )}
          </div>

          <input type="submit" value="Register" />
        </form>
      </div>
      <Bottom />
    </div>
  );
};

export default Register;